# coding: utf-8
# @Author: 莫小鱼
import pymysql
from AutoApiTest.unit_tools.handle_data.configParse import ConfigParse
from AutoApiTest.unit_tools.log_util import logs

conf = ConfigParse()


class ConnectMysql:
    """连接数据库"""

    def __init__(self):
        self.conf = {
            'host': conf.get_mysql_conf('host'),
            'prot': int(conf.get_mysql_conf('port')),
            'user': conf.get_mysql_conf('user'),
            'password': conf.get_mysql_conf('password'),
            'database': conf.get_mysql_conf('database')
        }

        try:
            self.conn = pymysql.connect(**self.conf)
            # 获取操作游标
            self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            logs.info(f"成功连接到数据库：【{self.conf.get('database')}】")
        except Exception as e:
            logs.error(f"连接数据库失败：【{self.conf.get('database')}】")

    def close(self):
        if self.conn and self.cursor:
            self.conn.close()
            self.cursor.close()
        logs.info("数据库连接关闭")
        return True

    def query(self, sql, fetchall=False):
        """
        查询数据库数据
        :param sql: 查询的sql语句
        :param fetchall: 查询全部数据，默认为Fales
        :return:
        """
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            if fetchall:
                res = self.cursor.fetchall()
            else:
                res = self.cursor.fetchone()
            return res
        except Exception as e:
            logs.error(f"查询数据库数据异常;{e}")
        finally:
            self.close()

    def delete(self, sql):
        """
        删除数据库内容
        :param sql: 删除sql语句
        :return:
        """
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            logs.info("删除成功")
        except Exception as e:
            logs.error(f"删除数据异常，{e}")
        finally:
            self.close()


